<?php
function pre($data) {
  echo '<pre>';
  print_r($data);
  echo '</pre>';
}

/**
 * 获得随机字符串
 * @param   Number  $len    需要的长度
 * @param   Bool    $special    是否需要特殊符号
 * @return  String  返回随机字符串
 */
function build_ranstr($len = 8, $special = false)
{
  $chars = array(
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
    "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
    "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
    "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
    "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
    "3", "4", "5", "6", "7", "8", "9"
  );

  if ($special) {
    $chars = array_merge($chars, array(
      "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
      "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
      "}", "<", ">", "~", "+", "=", ",", "."
    ));
  }

  $charsLen = count($chars) - 1;
  shuffle($chars);                            //打乱数组顺序
  $str = '';
  for ($i = 0; $i < $len; $i++) {
    $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
  }
  return $str;
}

/**
 *  todo 图片上传的函数
 */
function upload($name, $type = array('jpg', 'jpeg', 'png', 'gif', 'webp'), $size = 1048576, $upload = 'upload')
{
  // 判断文件夹是否存在
  if (!is_dir($upload)) {
    @mkdir($upload);
  }

  // 返回结果
  $result = [
    'code' => 0, // 状态码 1 成功 0 失败
    'msg' => '未知信息',
    'url' => null
  ];

  //1、判断错误值
  $error = $_FILES[$name]['error'];
  switch ($error) {
    case 1:
      $result['msg'] = '上传大小不能超过upload_max_filesize设置的值';
      return $result;
      break;
    case 2:
      $result['msg'] = '上传大小不能超过MAX_FILE_SIZE设置的值';
      return $result;
      break;
    case 3:
      $result['msg'] = '图片上传不完整';
      return $result;
      break;
    case 4:
      $result['msg'] = '没有选择图片';
      return $result;
      break;
  }
  //2、判断文件的类型
  $pre = pathinfo($_FILES[$name]['name'], PATHINFO_EXTENSION);
  if (!in_array($pre, $type)) { //后缀没有在$type里面出现
    return '上传的图片类型错误';
  }
  //3、再次限制图片大小
  $s = $_FILES[$name]['size'];
  if ($s > $size) {
    return '图片过大,请压缩后上传';
  }


  //4、保存图片
  //首先设置好保存之后图片的名称
  $file = date('YmdHis', time()) . mt_rand(1000, 9999) . mt_rand(1000, 9999) . '.' . $pre;

  if (is_uploaded_file($_FILES[$name]['tmp_name'])) {
    //先判断图片有没有上传到服务器的临时文件夹
    move_uploaded_file($_FILES[$name]['tmp_name'], $upload . '/' . $file);

    $result = array(
      'code' => 1,
      'url' =>  $file,
      'msg' => '图片上传成功'
    );
    return $result;
  } else {
    $result['msg'] = '上传图片失败';
    return  $result;
  }
}

/** 
 * todo 删除文件的方法
 */
function delfile($filename)
{
  // 打开某个目录
  $path = './upload/';

  //给定的目录不是一个文件
  if (!is_file($path . $filename)) {
    return null;
  }
  // echo $path . $filename;
  //删除文件
  unlink($path . $filename);

  return true;
}

/**
 * @param String $msg 提示信息
 * @param String $url 跳转地址
 * @return String $str 结果
 */
function ShowMsg(String $msg, $url = null)
{
  // 定义一个空字符串
  $str = '';
  if ($url) {
    $str = "
            <script>
                alert('$msg');
                location.href = '$url';
            </script>
        ";
  } else {
    $str = "
            <script>
                alert('$msg');
                history.go(-1);
            </script>
        ";
  }

  // 调用函数直接输出
  echo $str;
}

/** 
 * @param 封装查询所有方法
 * @param String $sql 查询语句
 * @param Array $dataList 返回结果
 */
function queryAll(String $sql)
{
  global $conn;

  $res = mysqli_query($conn, $sql);

  if (!$res) {
    echo 'SQL语句执行失败：' . $sql;
    exit;
  }

  $dataList = [];

  if ($res && mysqli_num_rows($res) > 0) {
    $dataList = mysqli_fetch_all($res, MYSQLI_ASSOC);
  }

  return $dataList;
}

/** 
 * @param 封装查询
 * @param String $sql 查询语句
 * @param Array $dataList 返回结果
 */
function query($sql)
{
  global $conn;
  $res = mysqli_query($conn, $sql);

  if ($res && mysqli_num_rows($res) > 0) {
    $data = mysqli_fetch_assoc($res);
  }

  return $data;
}

/** 
 * @param 封装插入方法
 * @param Array $data 插入数据
 * @param String $table 表名字
 * @param String $result 返回结果
 */
function insertInfo(String $table, array $data)
{
  global $conn;
  global $pre_;

  $table = $pre_ . $table;
  $key = array_keys($data);

  $fields = "`" . implode("`,`", $key) . "`";

  $values = "'" . implode("','", $data) . "'";

  $sql = "INSERT INTO $table($fields)VALUES($values)";

  //执行语句
  $res = mysqli_query($conn, $sql);

  if (!$res) {
    echo "SQL语句执行失败：" . $sql . "<br>";
    echo "错误信息：" . mysqli_error($conn);
    exit;
  }

  $result = array(
    'code' => 1,
    'data' => mysqli_insert_id($conn),
    'msg' => '插入成功'
  );
  return $result;
  exit;
}

/** 
 * @param 封装删除方法 - AJAX
 * @param String $table 表单
 * @param String $where 查询条件
 */
function deleteById($table,  $where = 1)
{
  global $conn;
  global $pre_;

  $table = $pre_ . $table;

  $sql = "DELETE FROM $table WHERE $where";
  $res = mysqli_query($conn, $sql);

  if (!$res) {
    echo 'SQL语句执行错误：' . $sql;
    echo '错误信息：' . mysqli_error($conn);
    exit;
  }

  $result = array(
    'code' => 1,
    'data' => mysqli_affected_rows($conn),
    'msg' => '删除成功'
  );
  echo json_encode($result);
  exit;
}

/** 
 * @param 封装更新方法
 * @param String $table 数据库表
 * @param Array $data 更新数据
 * @param String $where 查询条件
 */
function updataById($table, $data, $where = 1)
{
  global $conn;
  global $pre_;

  $table = $pre_ . $table;

  $str = "";

  foreach ($data as $key => $val) {
    $str .= "`$key` = '$val',";
  }

  $str = trim($str, ",");

  $sql = "UPDATE $table SET $str WHERE $where";

  $res = mysqli_query($conn, $sql);

  if (!$res) {
    echo 'SQL语句执行失败：' . $sql . '<br />';
    echo '错误信息：' . mysqli_error($conn);
    exit;
  }

  $result = array(
    'code' => 1,
    'data' => mysqli_affected_rows($conn),
    'msg' => '修改成功'
  );
  return $result;
  exit;
}

/**
 * @param ajax操作成功函数
 */

function success($msg = '未知信息', $data = null, $code = 1)
{
  $result = [
    'msg' => $msg,
    'data' => $data,
    'code' => $code
  ];

  echo json_encode($result);
  exit;
}

/**
 * @param ajax操作失败函数
 */

function error($msg = '未知信息', $data = null, $code = 0)
{
  $result = [
    'msg' => $msg,
    'data' => $data,
    'code' => $code
  ];

  echo json_encode($result);
  exit;
}

/**
 * @param 封装检查模块
 * @param String $table 表名
 */
function checkAll($table)
{
  global $pre_;

  $table = $pre_ . $table;
  $sql = "SELECT * FROM $table";
  $res = queryAll($sql);
  return $res;
}

/** 
 * @param 获取当前的网址   
 */

function get_url()
{
  // 获取当前的完整地址
  $str = $_SERVER['PHP_SELF'] . '?';

  if ($_GET) {
    foreach ($_GET as $k => $v) {
      if ($k != 'page') {
        $str .= $k . '=' . $v . '&';
      }
    }
  }

  return $str;
}

/** 
 * 
 * 分页函数
 * @param $current 当前页
 * @param $count   记录总数
 * @param $limit   每页显示多少条
 * @param $size    中间显示多少条
 * @param $class   样式
 * 
 */
function page($current, $count, $limit, $size, $class = '')
{
  $str = '';

  // todo 当数据总条数大于每一页显示的条数
  if ($count > $limit) {
    // 算出总页数
    $pages = ceil($count / $limit);
    // 获取当前页面的url（带有参数的）
    $url = get_url();
    // 开始拼接分页
    $str .= '<ul class="' . $class . '">';

    // 判断当前页是否是1
    if ($current == 1) {
      $str .= '<li class="disabled" role="button"><a href="#">首&nbsp;&nbsp;页</a></li>';
      $str .= '<li class="disabled" role="button"><a href="#">上一页</a></li>';
    } else {
      $str .= '<li><a href="' . $url . 'page=1">首&nbsp;&nbsp;页</a></li>';
      $str .= '<li><a href="' . $url . 'page=' . ($current - 1) . '">上一页</a></li>';
    }

    // 中间
    if ($current <= floor($size / 2)) {
      $start = 1;
      $end = $pages < $size ? $pages : $size;
    } elseif ($current >= $pages - floor($size / 2)) {
      $start = $pages - $size + 1 <= 0 ? 1 : $pages - $size + 1;
      $end = $pages;
    } else {
      $start = $current - floor($size / 2);
      $end = $current + floor($size / 2);
    }

    for ($i = $start; $i <= $end; $i++) {
      if ($i == $current) {
        $str .= '<li class="current disabled" role="button"><a href="#">' . $i . '</a></li>';
      } else {
        $str .= '<li><a href="' . $url . 'page=' . $i . '">' . $i . '</a></li>';
      }
    }

    //最后
    if ($pages == $current) {
      $str .= '<li class="disabled" role="button"><a href="#">下一页</a></li>';
      $str .= '<li class="disabled" role="button"><a href="#">尾&nbsp;&nbsp;页</a></li>';
    } else {
      $str .= '<li><a href="' . $url . 'page=' . ($current + 1) . '">下一页</a></li>';
      $str .= '<li><a href="' . $url . 'page=' . $pages . '">尾&nbsp;&nbsp;页 </a></li>';
    }

    $str .= '</ul>';

  }


  return $str;
}
